#include "LogSystem.h"

LogSystem* LogSystem::mInstance = new LogSystem();

LogSystem* LogSystem::getInstance()
{

	assert( mInstance );
	return mInstance;

}

LogSystem::LogSystem()
	: mOutStream(NULL)
{

}

LogSystem::~LogSystem()
{

	if ( mOutStream )
		fclose(mOutStream);
	success("~LogSystem");

}

void LogSystem::log(const char* format, const char* title, va_list& ap)
{

	char _buf[MAX_LINE_LENGTH], _buf2[MAX_LINE_LENGTH];
	time_t _rawtime;
	struct tm* _timeinfo;

	// Get hour and minutes
	time(&_rawtime);
	_timeinfo = localtime(&_rawtime);
	strftime(_buf, 80, "[%d-%m-%Y %H:%M:%S]", _timeinfo);

	// Adding title and formating
	strcat(_buf, title);
	strcat(_buf, format);

	vsprintf(_buf2, _buf, ap);
	va_end(ap);
	puts(_buf2);

#ifdef WIN32
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TNORMAL);
#endif

	if( mOutStream != NULL )
	{

		fputs(_buf2, mOutStream);
		putc('\n', mOutStream);

	}

}

void LogSystem::warning(const char* format,...)
{

	va_list _ap;
	char _buf[LOG_MAX_TITLE_LENGTH];

	va_start(_ap, format);

#ifdef WIN32
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TYELLOW);
	strcpy(_buf, "[WARNING]:");
#else
	strcpy(_buf, colorstrings[TYELLOW]);
	strcat(_buf, "[WARNING]:");
	strcat(_buf, colorstrings[TNORMAL]);
#endif

	log(format, _buf, _ap);

}

void LogSystem::info(const char* format,...)
{

	va_list _ap;
	char _buf[LOG_MAX_TITLE_LENGTH];

	va_start(_ap, format);

#ifdef WIN32
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
	strcpy(_buf, "[INFO]:");
#else
	strcpy(_buf, colorstrings[TWHITE]);
	strcat(_buf, "[INFO]:");
	strcat(_buf, colorstrings[TNORMAL]);
#endif

	log(format, _buf, _ap);

}

void LogSystem::error(const char* format,...)
{

	va_list _ap;
	char _buf[LOG_MAX_TITLE_LENGTH];

	// Initialize params
	va_start(_ap, format);

#ifdef WIN32
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TRED);
	strcpy(_buf, "[ERROR]:");
#else
	strcpy(_buf, colorstrings[TRED]);
	strcat(_buf, "[ERROR]:");
	strcat(_buf, colorstrings[TNORMAL]);
#endif

	log(format, _buf, _ap);

}

void LogSystem::success(const char* format,...)
{

	va_list _ap;
	char _buf[LOG_MAX_TITLE_LENGTH];

	// Initialize params
	va_start(_ap, format);

#ifdef WIN32
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TGREEN);
	strcpy(_buf, "[SUCCESS]:");
#else
	strcpy(_buf, colorstrings[TGREEN]);
	strcat(_buf, "[SUCCESS]:");
	strcat(_buf, colorstrings[TNORMAL]);
#endif

	log(format, _buf, _ap);

}

void LogSystem::setOutputFile(const char* fileName)
{

	FILE* _fp = fopen(fileName, "w");

	if ( _fp == NULL )
		Log->error("Error al crear el fichero de log %s.", fileName);
	else
		mOutStream = _fp;

}

void LogSystem::stop()
{

	Log->success("LogSystem stopped");
	delete Log;

}
